package com.eco.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eco.bean.Liabilities;
import com.eco.service.LiabilitiesService;
import com.eco.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("liabilities")
@CrossOrigin
public class LiabilitiesController {

    @Autowired
    private LiabilitiesService liabilitiesService;

    @GetMapping("list")
    public Result getList() {
        List<Liabilities> list = liabilitiesService.list();
        return Result.success(list);
    }

    @PostMapping("/")
    public Result add(@RequestBody Liabilities liabilities) {
        liabilitiesService.save(liabilities);
        Liabilities savedLiability = liabilitiesService.getById(liabilities.getLiabilityId());
        return Result.success("保存成功", savedLiability);
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable("id") String id) {
        boolean success = liabilitiesService.removeById(id);
        if (success) {
            return Result.success("删除成功", null);
        } else {
            return Result.fail(201, "删除失败");
        }
    }

    @PutMapping
    public Result edit(@RequestBody Liabilities liabilities) {
        boolean success = liabilitiesService.saveOrUpdate(liabilities);
        Liabilities updated = liabilitiesService.getById(liabilities.getLiabilityId());
        if (success) {
            return Result.success("保存成功", updated);
        } else {
            return Result.fail(500, "保存失败");
        }
    }

    @GetMapping("page")
    public Result getPage(Page page, @RequestParam("searchText") String searchText) {
        IPage<Liabilities> result;
        if (searchText == null || searchText.isEmpty()) {
            result = liabilitiesService.page(page);
        } else {
            QueryWrapper<Liabilities> wrapper = new QueryWrapper<>();
            wrapper.like("liability_type", searchText);
            result = liabilitiesService.page(page, wrapper);
        }
        return Result.success(result);
    }
}
